from rest_framework import serializers
from .models import ZtProject, ZtModule

#项目详细信息序列化
class ZtProjectDetailSerializer(serializers.ModelSerializer):

    #获取真实姓名
    pm = serializers.SerializerMethodField()

    class Meta:
        model = ZtProject
        fields = ['id', 'project','name', 'type', 'PM','pm', 'teamCount','budget',
                  'begin', 'end', 'status', 'desc','end','begin']

    def get_pm(self, obj):
        '''
        获取pm对应的真实姓名
        '''

        # 获取关联的User对象
        try:
            PM = obj.PM
        except:
            # PM字段为空（没有PM字段）
            return ''
        # 如果存在关联的User对象，则返回其realname，否则返回None
        return PM.realname if PM else ''

    def get_translated_fields(self, obj):
        '''
        转换字段
        '''

        #转换关系
        hasProduct_map = {
            0:"项目型项目",
            1:"产品型项目",
        }

        status_map = {
            'wait': "未开始",
            'doing': "进行中",
            'suspended': "已挂起",
            'closed': "已关闭",
            'delay': "已延期",
        }

        # 定义一个字典，键是字段名，值是转换函数
        translations = {
            'hasProduct': lambda value: hasProduct_map[value],
            'status': lambda value: status_map[value],
        }

        # 获取原始值
        original_values = {field_name: getattr(obj, field_name) for field_name in translations}

        # 应用转换
        translated_values = {field_name: translations[field_name](original_value) for field_name, original_value in
                             original_values.items()}

        return translated_values

    def to_representation(self, instance):
        '''
        更新为转换后的值
        '''
        # 获取转换后的值
        translated_values = self.get_translated_fields(instance)

        # 将转换后的值添加到原始序列化器的数据中
        data = super(ZtProjectDetailSerializer, self).to_representation(instance)
        data.update(translated_values)

        return data

#所有项目信息序列化
class ZtProjectSerializer(serializers.ModelSerializer):

    class Meta:
        model = ZtProject
        fields = ['id', 'name']

#模块项目信息序列化
class ZtModuleSerializer(serializers.ModelSerializer):

    class Meta:
        model = ZtModule
        fields = ['id', 'name']
